#pragma once
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string>
#include <strings.h>
#include "common.hpp"


class InetAddr
{
public:
    InetAddr(sockaddr_in &addr)
        :_addr(addr)
    {
        _port = ntohs(addr.sin_port);
        //这种方式有局限性，可以理解为只能转4不能转6
        //_ip = inet_ntoa(addr.sin_addr);
        char ipBuffer[100];
        inet_ntop(AF_INET, &addr.sin_addr, ipBuffer, sizeof(sockaddr_in));
        _ip = ipBuffer;
    }

    //主机转网络
    //
    InetAddr(uint16_t port, std::string ip)
        :_port(port)
        ,_ip(ip)
    {
        bzero(&_addr, sizeof(_addr));
        inet_pton(AF_INET, ip.c_str(), &_addr.sin_addr);
        _addr.sin_family = AF_INET;
        _addr.sin_port = htons(port);
    }

    uint16_t Port()
    {
        return _port;
    }

    std::string Ip()
    {
        return _ip;
    }
    
    std::string AddrMessage()
    {
        return "[" + _ip + " | " + std::to_string(_port) + "]";
    }

    bool operator==(InetAddr &tmp)
    {
        return tmp._ip == _ip && tmp._port == _port;
    }

    sockaddr_in& Sockaddr_in()
    {
        return _addr;
    }

    sockaddr* Sockaddr()
    {
        return CONV(&_addr);
    }
private:
    sockaddr_in _addr;
    uint16_t _port;
    std::string _ip;
};